﻿//Main ViewModel  
//author: Alexis 2011-06-18
//blog: http://www.cnblogs.com/alexis/

using MvvmLight;
using MvvmLight.Command;
using System.Collections.ObjectModel;
using AccountHelper.Model;
using AccountHelper.Common;
using System.Collections.Generic;
using MvvmLight.Messaging;
using System;
using Microsoft.Phone.Tasks;
using System.Linq;
using System.Windows;
using Microsoft.Phone.Shell;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.IO.IsolatedStorage;
using Microsoft.Phone;

namespace AccountHelper.ViewModel
{
    public class MainViewModel : ViewModelBase
    {
        #region Property

        private ObservableCollection<Money> _costsMoney;
        public ObservableCollection<Money> CostsMoney
        {
            get
            {
                return _costsMoney;
            }
            set
            {
                _costsMoney = value;
                RaisePropertyChanged(() => CostsMoney);
            }
        }

        private ObservableCollection<Money> _chargesMoney;
        public ObservableCollection<Money> ChargesMoney
        {
            get
            {
                return _chargesMoney;
            }
            set
            {
                _chargesMoney = value;
                RaisePropertyChanged(() => ChargesMoney);
            }
        }

        public ObservableCollection<MenuItem> MenuList { get; set; }

        public bool IsFirstLoad { get; set; }

        private User _currentUser;
        public User CurrentUser
        {
            get
            {
                if (_currentUser==null)
                {
                    _currentUser=UserInfo.userInfo;
                }
                return _currentUser;
            }
            set
            {
                _currentUser = value;
                if (UserInfo.userInfo != null && UserInfo.userInfo.ProfileImageUri != null)
                {
                    if (UserInfo.userInfo.ProfileImageUri.ToString() != "/Images/a97911.jpg")
                    {
                        var isoFile = IsolatedStorageFile.GetUserStoreForApplication();
                        using (var stream = isoFile.OpenFile(UserInfo.userInfo.ProfileImageUri.ToString(), System.IO.FileMode.Open))
                        {
                            ProfileImage = new BitmapImage();
                            ProfileImage.SetSource(stream);
                        }
                    }
                    else
                    {
                        ProfileImage = new BitmapImage { UriSource = UserInfo.userInfo.ProfileImageUri };
                    }
                }
                RaisePropertyChanged("CurrentUser");
            }
        }

        private BitmapImage _profileImage;
        public BitmapImage ProfileImage
        {
            get
            {
                return _profileImage;
            }
            set
            {
                _profileImage = value;
                RaisePropertyChanged(() => ProfileImage);
            }
        }

        private AccountDataContext db;

        private int selectIndex;
        public int SelectIndex
        {
            get
            {
                return selectIndex;
            }
            set
            {
                selectIndex = value;
                switch (value)
                {
                    case 0://menu
                        break;
                    case 1://cost list
                        if (null == CostsMoney || CostsMoney.Count == 0)
                        {
                            LoadCost();
                        }
                        break;
                    case 2://chagre list
                        if (null == ChargesMoney || ChargesMoney.Count == 0)
                        {
                            
                            LoadCharge();
                            
                        }
                        break;
                    case 3://profile
                        break;
                    default:
                        break;
                }
                RaisePropertyChanged("SelectIndex");
            }
        }

        #endregion

        #region Constructor

        /// <summary>
        /// Initializes a new instance of the MainViewModel class.
        /// </summary>
        public MainViewModel()
        {
            ChargesMoney = new ObservableCollection<Money>();
            InitData();
            InitMenu();
            IsFirstLoad = false;
        }

        private void InitData()
        {
            string DBConnectionString = "Data Source=isostore:/Account.sdf";
            db = new AccountDataContext(DBConnectionString);

            if (!db.DatabaseExists())
            {
                db.CreateDatabase();
                db.SubmitChanges();
            }

            LoadCost();

        }
        #endregion

        #region Command

        private RelayCommand<MenuType> menuCommand;
        public RelayCommand<MenuType> MenuCommand
        {
            get
            {
                return menuCommand ?? (menuCommand = new RelayCommand<MenuType>((p) =>
                {
                    switch (p)
                    {
                        case MenuType.New:
                            Messenger.Default.Send<Uri>(new Uri("/View/NewChargeView.xaml", UriKind.Relative), "Navigation");
                            break;
                        case MenuType.Chart:
                            Messenger.Default.Send<Uri>(new Uri("/View/ChartView.xaml", UriKind.Relative), "Navigation");
                            break;
                        case MenuType.Setting:
                            ViewModelLocator.Instance.SettingVM.SettingsSelectIndex = 0;
                            ViewModelLocator.Instance.SettingVM.UserName = UserInfo.userInfo.UserName;
                            Messenger.Default.Send<Uri>(new Uri("/View/SettingView.xaml", UriKind.Relative), "Navigation");
                            break;
                        case MenuType.About:
                            ViewModelLocator.Instance.SettingVM.SettingsSelectIndex = 1;
                            Messenger.Default.Send<Uri>(new Uri("/View/SettingView.xaml", UriKind.Relative), "Navigation");
                            break;
                        case MenuType.Account:
                            Messenger.Default.Send<int>(3, "MainView_SelectedIndex");
                            break;
                        case MenuType.Mail:
                            SendMail();
                            break;
                        default:
                            break;
                    }
                }));
            }
        }

        private RelayCommand<string> newFromImageCommand;
        public RelayCommand<string> NewFromImageCommand
        {
            get
            {
                return newFromImageCommand??(newFromImageCommand=new RelayCommand<string>((p)=>
                {
                    if (p=="cost")
                    {
                        ViewModelLocator.Instance.NewChargeVM.SelectType = new KeyValuePair<string, ChargeType>("支出", ChargeType.Cost);
                    }
                    else
                    {
                        ViewModelLocator.Instance.NewChargeVM.SelectType = new KeyValuePair<string, ChargeType>("收入", ChargeType.Charge);
                    }
                    Messenger.Default.Send<Uri>(new Uri("/View/NewChargeView.xaml", UriKind.Relative), "Navigation");
                })); 
            }
        }

        private RelayCommand<Money> addNewMoneyCommand;
        public RelayCommand<Money> AddNewMoneyCommand
        {
            get
            {
                return addNewMoneyCommand ?? (addNewMoneyCommand = new RelayCommand<Money>(p =>
                    {
                        Deployment.Current.Dispatcher.BeginInvoke(delegate
                        {
                            if (p.Type == ChargeType.Charge)
                            {
                                this.ChargesMoney.Add(p);
                                UserInfo.userInfo.CurCharge += p.Amount;
                            }
                            else
                            {
                                this.CostsMoney.Add(p);
                                UserInfo.userInfo.CurCost += p.Amount;
                            }
                        });
                        db.Items.InsertOnSubmit(p);
                        db.SubmitChanges();
                    }));
            }
        }

        private RelayCommand<Money> copyCommand;
        public RelayCommand<Money> CopyCommand
        {
            get
            {
                return copyCommand ?? (copyCommand = new RelayCommand<Money>(p =>
                {
                    EditOrNew(p);
                }));
            }
        }


        private RelayCommand<Money> editCommand;
        public RelayCommand<Money> EditCommand
        {
            get
            {
                return editCommand ?? (editCommand = new RelayCommand<Money>(p =>
                {
                    ViewModelLocator.Instance.NewChargeVM.ChargeId = p.MoneyId;
                    EditOrNew(p);
                }));
            }
        }

        private RelayCommand<Money> updateCommand;
        public RelayCommand<Money> UpdateCommand
        {
            get
            {
                return updateCommand ?? (updateCommand = new RelayCommand<Money>(p =>
                {
                    var item=db.Items.First(x => x.MoneyId == p.MoneyId) as Money;                    
                    if (item!=null)
                    {
                        //find index
                        int index = ChargesMoney.IndexOf(item) > 0 ? ChargesMoney.IndexOf(item) : CostsMoney.IndexOf(item);

                        if (p.Type == ChargeType.Charge)
                        {
                            ChargesMoney[index] = item;
                            UserInfo.userInfo.CurCharge = UserInfo.userInfo.CurCharge - item.Amount + p.Amount;
                        }
                        else
                        {
                            CostsMoney[index] = item;
                            UserInfo.userInfo.CurCost = UserInfo.userInfo.CurCost - item.Amount + p.Amount;
                        }
                        item.ChargeTitle=p.ChargeTitle;
                        item.ChargeDate=p.ChargeDate;
                        item.Amount = p.Amount;
                        item.Type = p.Type;

                        db.SubmitChanges();
                    }
                }));
            }
        }

        private RelayCommand<Money> deleteCommand;
        public RelayCommand<Money> DeleteCommand
        {
            get
            {
                return deleteCommand ?? (deleteCommand = new RelayCommand<Money>(p =>
                {
                    if (MessageBox.Show("确定要删除这条费用？", "", MessageBoxButton.OKCancel) == MessageBoxResult.Cancel)
                    {
                        return;
                    }
                    Deployment.Current.Dispatcher.BeginInvoke(delegate
                    {
                        if (p.Type == ChargeType.Charge)
                        {
                            this.ChargesMoney.Remove(p);
                            UserInfo.userInfo.CurCharge -= p.Amount;
                        }
                        else
                        {
                            this.CostsMoney.Remove(p);
                            UserInfo.userInfo.CurCost -= p.Amount;
                        }
                    });
                    db.Items.DeleteOnSubmit(p);
                    db.SubmitChanges();
                }));
            }
        }

        private RelayCommand pinToStartCommand;
        public RelayCommand PinToStartCommand
        {
            get
            {
                return pinToStartCommand ?? (pinToStartCommand = new RelayCommand(() =>
                    {
#if DEBUG
                        var items = ShellTile.ActiveTiles;
                        if (null != items)
                        {
                            foreach (var item in items)
                            {
                                System.Diagnostics.Debug.WriteLine("Current Tile Uri :" + item.NavigationUri.ToString());
                            }
                        }
#endif

                        //just pin main view my profile to start
                        Uri u = new Uri("/View/MainView.xaml?selectIndex=3", UriKind.Relative);
                        if (!ShellTileHelper.IsPinned(u))
                        {
                            Uri profile = new Uri("isostore:"+CurrentUser.ProfileImageUri.ToString());
                            if (UserInfo.userInfo.ProfileImageUri.ToString() == "/Images/a97911.jpg")
                            {
                                profile = new Uri("/Images/a97911.jpg", UriKind.Relative);
                            }
                            StandardTileData std = new StandardTileData
                            {
                                Title = "账户助手",
                                BackgroundImage = new Uri("Background.png", UriKind.Relative),
                                BackTitle =CurrentUser.UserName,
                                BackBackgroundImage = profile,
                            };
                            ShellTileHelper.Pin(u, std);
                        }

                        //note :  Our App will be Deactivated if you do Pin To Start                        
                    }));
            }
        }


        #endregion

        #region method
        private void InitMenu()
        {
            MenuList = new ObservableCollection<MenuItem>();
            MenuList.Clear();
            //new charge menu
            MenuList.Add(new MenuItem()
            {
                MenuName = "新增费用",
                IcoUrl = ResourcesConstants.MenuNew,
                Type = MenuType.New
            });
            //my account menu
            MenuList.Add(new MenuItem()
            {
                MenuName = "我的账户",
                IcoUrl = ResourcesConstants.MenuAccount,
                Type = MenuType.Account
            });
            //send mail menu
            MenuList.Add(new MenuItem()
            {
                MenuName = "联系我",
                IcoUrl = ResourcesConstants.MenuMail,
                Type = MenuType.Mail
            });
            //setting menu
            MenuList.Add(new MenuItem()
            {
                MenuName = "设置",
                IcoUrl = ResourcesConstants.MenuSetting,
                Type = MenuType.Setting
            });
            //about menu
            MenuList.Add(new MenuItem()
            {
                MenuName = "关于",
                IcoUrl = ResourcesConstants.MenuAbout,
                Type = MenuType.About
            });
        }

        private void SendMail()
        {
            try
            {
                EmailComposeTask mail = new EmailComposeTask() { To = ResourcesConstants.EmailAddress };
                mail.Show();
            }
            catch (Exception ex)
            {
                throw;
            }
        }

        private void LoadCharge()
        {
            if (ChargesMoney != null && ChargesMoney.Count > 0)
            {
                ChargesMoney.Clear();
            }
            var allCharges = from Money m in db.Items
                             where (m.Type == ChargeType.Charge)
                             select m;
            foreach (var item in allCharges)
            {
                this.ChargesMoney.Add(item);
            }
        }

        private void LoadCost()
        {
            var allCost = from Money m in db.Items
                          where (m.Type == ChargeType.Cost)
                          select m;
            CostsMoney = new ObservableCollection<Money>(allCost);
        }

        private void EditOrNew(Money p)
        {
            ViewModelLocator.Instance.NewChargeVM.ChargeTitle = p.ChargeTitle;
            ViewModelLocator.Instance.NewChargeVM.DtDate = Convert.ToDateTime(p.ChargeDate);
            ViewModelLocator.Instance.NewChargeVM.MAmount = p.Amount;
            if (p.Type == ChargeType.Charge)
            {
                ViewModelLocator.Instance.NewChargeVM.SelectType = new KeyValuePair<string, ChargeType>("收入", ChargeType.Charge);
            }
            else
            {
                ViewModelLocator.Instance.NewChargeVM.SelectType = new KeyValuePair<string, ChargeType>("支出", ChargeType.Cost);
            }
            Messenger.Default.Send<Uri>(new Uri("/View/NewChargeView.xaml", UriKind.Relative), "Navigation");
        }

        #endregion

    }
}